<!DOCTYPE html>
<html lang="en-US">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width,initial-scale=1">
    <title>1 初识 Node.js 与内置模块 | HasakWebBlog</title>
    <meta name="generator" content="VuePress 1.9.7">
    <link rel="icon" href="/favicon.ico">
    <meta name="description" content="hasak">
    <meta name="viewport" content="width=device-width,initial-scale=1,user-scalable=no">
    
    <link rel="preload" href="/assets/css/0.styles.a5a0d673.css" as="style"><link rel="preload" href="/assets/js/app.c7915c77.js" as="script"><link rel="preload" href="/assets/js/3.f80332a6.js" as="script"><link rel="preload" href="/assets/js/1.5cffa4a1.js" as="script"><link rel="preload" href="/assets/js/44.d579b00f.js" as="script"><link rel="prefetch" href="/assets/js/10.02ae8499.js"><link rel="prefetch" href="/assets/js/11.c5238d8f.js"><link rel="prefetch" href="/assets/js/12.be21fd80.js"><link rel="prefetch" href="/assets/js/13.bd684308.js"><link rel="prefetch" href="/assets/js/14.b5f9fc77.js"><link rel="prefetch" href="/assets/js/15.318683dc.js"><link rel="prefetch" href="/assets/js/16.74f9d94e.js"><link rel="prefetch" href="/assets/js/17.cd1e6d69.js"><link rel="prefetch" href="/assets/js/18.901e5492.js"><link rel="prefetch" href="/assets/js/19.417d2070.js"><link rel="prefetch" href="/assets/js/20.39ec66a2.js"><link rel="prefetch" href="/assets/js/21.fbf1aaf8.js"><link rel="prefetch" href="/assets/js/22.736aeb98.js"><link rel="prefetch" href="/assets/js/23.abcdc310.js"><link rel="prefetch" href="/assets/js/24.26658596.js"><link rel="prefetch" href="/assets/js/25.40bdc691.js"><link rel="prefetch" href="/assets/js/26.29ac009b.js"><link rel="prefetch" href="/assets/js/27.edc6afbf.js"><link rel="prefetch" href="/assets/js/28.b9c1065e.js"><link rel="prefetch" href="/assets/js/29.b46f8f9e.js"><link rel="prefetch" href="/assets/js/30.6839ae7e.js"><link rel="prefetch" href="/assets/js/31.85913f4e.js"><link rel="prefetch" href="/assets/js/32.098b21df.js"><link rel="prefetch" href="/assets/js/33.faced894.js"><link rel="prefetch" href="/assets/js/34.239b19e7.js"><link rel="prefetch" href="/assets/js/35.5c8a8406.js"><link rel="prefetch" href="/assets/js/36.46f0ebac.js"><link rel="prefetch" href="/assets/js/37.2456f410.js"><link rel="prefetch" href="/assets/js/38.b76624ee.js"><link rel="prefetch" href="/assets/js/39.64ecef14.js"><link rel="prefetch" href="/assets/js/4.7d7a493e.js"><link rel="prefetch" href="/assets/js/40.a1304a44.js"><link rel="prefetch" href="/assets/js/41.f98208ce.js"><link rel="prefetch" href="/assets/js/42.f0be4a4c.js"><link rel="prefetch" href="/assets/js/43.1a46f61e.js"><link rel="prefetch" href="/assets/js/45.8e8ea47a.js"><link rel="prefetch" href="/assets/js/46.1b194721.js"><link rel="prefetch" href="/assets/js/47.994c7d71.js"><link rel="prefetch" href="/assets/js/48.f17a641c.js"><link rel="prefetch" href="/assets/js/49.0d9ea06f.js"><link rel="prefetch" href="/assets/js/5.176296fc.js"><link rel="prefetch" href="/assets/js/50.e36885a9.js"><link rel="prefetch" href="/assets/js/51.64538ee2.js"><link rel="prefetch" href="/assets/js/52.1fd24c2e.js"><link rel="prefetch" href="/assets/js/53.967b1458.js"><link rel="prefetch" href="/assets/js/54.05b15a98.js"><link rel="prefetch" href="/assets/js/55.3c78b9d4.js"><link rel="prefetch" href="/assets/js/56.8d130c30.js"><link rel="prefetch" href="/assets/js/57.0008c022.js"><link rel="prefetch" href="/assets/js/58.4b49a382.js"><link rel="prefetch" href="/assets/js/59.8bb182dc.js"><link rel="prefetch" href="/assets/js/6.90835ce9.js"><link rel="prefetch" href="/assets/js/60.93235335.js"><link rel="prefetch" href="/assets/js/61.78370acd.js"><link rel="prefetch" href="/assets/js/62.1144f314.js"><link rel="prefetch" href="/assets/js/63.7fb72cd2.js"><link rel="prefetch" href="/assets/js/64.de8ba1be.js"><link rel="prefetch" href="/assets/js/65.cefa274d.js"><link rel="prefetch" href="/assets/js/66.32ad44bf.js"><link rel="prefetch" href="/assets/js/67.558c356c.js"><link rel="prefetch" href="/assets/js/68.15a3af19.js"><link rel="prefetch" href="/assets/js/69.b1b26c0a.js"><link rel="prefetch" href="/assets/js/7.2c075495.js"><link rel="prefetch" href="/assets/js/70.cb9b8e94.js"><link rel="prefetch" href="/assets/js/71.e371986a.js"><link rel="prefetch" href="/assets/js/72.a8af9117.js"><link rel="prefetch" href="/assets/js/73.dcc5a1af.js"><link rel="prefetch" href="/assets/js/74.803a909b.js"><link rel="prefetch" href="/assets/js/75.8129f8f6.js"><link rel="prefetch" href="/assets/js/76.ffcb07fc.js"><link rel="prefetch" href="/assets/js/8.9b4cfefe.js"><link rel="prefetch" href="/assets/js/9.e529cf11.js">
    <link rel="stylesheet" href="/assets/css/0.styles.a5a0d673.css">
  </head>
  <body>
    <div id="app" data-server-rendered="true"><div class="theme-container no-sidebar" data-v-7dd95ae2><div data-v-7dd95ae2><div class="password-shadow password-wrapper-out" style="display:none;" data-v-59e6cb88 data-v-7dd95ae2 data-v-7dd95ae2><h3 class="title" data-v-59e6cb88>HasakWebBlog</h3> <p class="description" data-v-59e6cb88>hasak</p> <label id="box" class="inputBox" data-v-59e6cb88><input type="password" value="" data-v-59e6cb88> <span data-v-59e6cb88>Konck! Knock!</span> <button data-v-59e6cb88>OK</button></label> <div class="footer" data-v-59e6cb88><span data-v-59e6cb88><i class="iconfont reco-theme" data-v-59e6cb88></i> <a target="blank" href="https://vuepress-theme-reco.recoluan.com" data-v-59e6cb88>vuePress-theme-reco</a></span> <span data-v-59e6cb88><i class="iconfont reco-copyright" data-v-59e6cb88></i> <a data-v-59e6cb88><span data-v-59e6cb88>hasak</span>
          
        <span data-v-59e6cb88>2022 - </span>
        2023
      </a></span></div></div> <div class="hide" data-v-7dd95ae2><header class="navbar" data-v-7dd95ae2><div class="sidebar-button"><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" role="img" viewBox="0 0 448 512" class="icon"><path fill="currentColor" d="M436 124H12c-6.627 0-12-5.373-12-12V80c0-6.627 5.373-12 12-12h424c6.627 0 12 5.373 12 12v32c0 6.627-5.373 12-12 12zm0 160H12c-6.627 0-12-5.373-12-12v-32c0-6.627 5.373-12 12-12h424c6.627 0 12 5.373 12 12v32c0 6.627-5.373 12-12 12zm0 160H12c-6.627 0-12-5.373-12-12v-32c0-6.627 5.373-12 12-12h424c6.627 0 12 5.373 12 12v32c0 6.627-5.373 12-12 12z"></path></svg></div> <a href="/" class="home-link router-link-active"><img src="/logo.png" alt="HasakWebBlog" class="logo"> <span class="site-name">HasakWebBlog</span></a> <div class="links"><div class="color-picker"><a class="color-button"><i class="iconfont reco-color"></i></a> <div class="color-picker-menu" style="display:none;"><div class="mode-options"><h4 class="title">Choose mode</h4> <ul class="color-mode-options"><li class="dark">dark</li><li class="auto active">auto</li><li class="light">light</li></ul></div></div></div> <div class="search-box"><i class="iconfont reco-search"></i> <input aria-label="Search" autocomplete="off" spellcheck="false" value=""> <!----></div> <nav class="nav-links can-hide"><div class="nav-item"><a href="/" class="nav-link"><i class="iconfont reco-home"></i>
  Home
</a></div><div class="nav-item"><div class="dropdown-wrapper"><a class="dropdown-title"><span class="title"><i class="iconfont reco-category"></i>
      前端学习
    </span> <span class="arrow right"></span></a> <ul class="nav-dropdown" style="display:none;"><li class="dropdown-item"><!----> <a href="/categories/HTML5&amp;CSS3/" class="nav-link"><i class="undefined"></i>
  HTML5&amp;CSS3
</a></li><li class="dropdown-item"><!----> <a href="/categories/Javascript/" class="nav-link"><i class="undefined"></i>
  Javascript
</a></li><li class="dropdown-item"><!----> <a href="/categories/Node/" class="nav-link"><i class="undefined"></i>
  Node
</a></li><li class="dropdown-item"><!----> <a href="/categories/VUE/" class="nav-link"><i class="undefined"></i>
  VUE
</a></li></ul></div></div><div class="nav-item"><a href="/tag/" class="nav-link"><i class="iconfont reco-tag"></i>
  Tags
</a></div><div class="nav-item"><a href="/timeline/" class="nav-link"><i class="iconfont reco-date"></i>
  时间轴
</a></div><div class="nav-item"><div class="dropdown-wrapper"><a class="dropdown-title"><span class="title"><i class="iconfont reco-message"></i>
      联系我
    </span> <span class="arrow right"></span></a> <ul class="nav-dropdown" style="display:none;"><li class="dropdown-item"><!----> <a href="https://github.com/hasakxu" target="_blank" rel="noopener noreferrer" class="nav-link external"><i class="iconfont reco-github"></i>
  GitHub
  <span><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg> <span class="sr-only">(opens new window)</span></span></a></li></ul></div></div> <!----></nav></div></header> <div class="sidebar-mask" data-v-7dd95ae2></div> <aside class="sidebar" data-v-7dd95ae2><div class="personal-info-wrapper" data-v-1fad0c41 data-v-7dd95ae2><img src="/dog.png" alt="author-avatar" class="personal-img" data-v-1fad0c41> <h3 class="name" data-v-1fad0c41>
    hasak
  </h3> <div class="num" data-v-1fad0c41><div data-v-1fad0c41><h3 data-v-1fad0c41>66</h3> <h6 data-v-1fad0c41>Articles</h6></div> <div data-v-1fad0c41><h3 data-v-1fad0c41>5</h3> <h6 data-v-1fad0c41>Tags</h6></div></div> <ul class="social-links" data-v-1fad0c41></ul> <hr data-v-1fad0c41></div> <nav class="nav-links"><div class="nav-item"><a href="/" class="nav-link"><i class="iconfont reco-home"></i>
  Home
</a></div><div class="nav-item"><div class="dropdown-wrapper"><a class="dropdown-title"><span class="title"><i class="iconfont reco-category"></i>
      前端学习
    </span> <span class="arrow right"></span></a> <ul class="nav-dropdown" style="display:none;"><li class="dropdown-item"><!----> <a href="/categories/HTML5&amp;CSS3/" class="nav-link"><i class="undefined"></i>
  HTML5&amp;CSS3
</a></li><li class="dropdown-item"><!----> <a href="/categories/Javascript/" class="nav-link"><i class="undefined"></i>
  Javascript
</a></li><li class="dropdown-item"><!----> <a href="/categories/Node/" class="nav-link"><i class="undefined"></i>
  Node
</a></li><li class="dropdown-item"><!----> <a href="/categories/VUE/" class="nav-link"><i class="undefined"></i>
  VUE
</a></li></ul></div></div><div class="nav-item"><a href="/tag/" class="nav-link"><i class="iconfont reco-tag"></i>
  Tags
</a></div><div class="nav-item"><a href="/timeline/" class="nav-link"><i class="iconfont reco-date"></i>
  时间轴
</a></div><div class="nav-item"><div class="dropdown-wrapper"><a class="dropdown-title"><span class="title"><i class="iconfont reco-message"></i>
      联系我
    </span> <span class="arrow right"></span></a> <ul class="nav-dropdown" style="display:none;"><li class="dropdown-item"><!----> <a href="https://github.com/hasakxu" target="_blank" rel="noopener noreferrer" class="nav-link external"><i class="iconfont reco-github"></i>
  GitHub
  <span><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg> <span class="sr-only">(opens new window)</span></span></a></li></ul></div></div> <!----></nav> <!----> </aside> <div class="password-shadow password-wrapper-in" style="display:none;" data-v-59e6cb88 data-v-7dd95ae2><h3 class="title" data-v-59e6cb88>1 初识 Node.js 与内置模块</h3> <!----> <label id="box" class="inputBox" data-v-59e6cb88><input type="password" value="" data-v-59e6cb88> <span data-v-59e6cb88>Konck! Knock!</span> <button data-v-59e6cb88>OK</button></label> <div class="footer" data-v-59e6cb88><span data-v-59e6cb88><i class="iconfont reco-theme" data-v-59e6cb88></i> <a target="blank" href="https://vuepress-theme-reco.recoluan.com" data-v-59e6cb88>vuePress-theme-reco</a></span> <span data-v-59e6cb88><i class="iconfont reco-copyright" data-v-59e6cb88></i> <a data-v-59e6cb88><span data-v-59e6cb88>hasak</span>
          
        <span data-v-59e6cb88>2022 - </span>
        2023
      </a></span></div></div> <div data-v-7dd95ae2><div data-v-7dd95ae2><main class="page" style="padding-right:0;"><section style="display:;"><div class="page-title"><h1 class="title">1 初识 Node.js 与内置模块</h1> <div data-v-8a445198><i class="iconfont reco-account" data-v-8a445198><span data-v-8a445198>hasak</span></i> <i class="iconfont reco-date" data-v-8a445198><span data-v-8a445198>6/25/2022</span></i> <!----> <i class="tags iconfont reco-tag" data-v-8a445198><span class="tag-item" data-v-8a445198>Node</span></i></div></div> <div class="theme-reco-content content__default"><h1 id="_1-初识-node-js-与内置模块"><a href="#_1-初识-node-js-与内置模块" class="header-anchor">#</a> 1. 初识 Node.js 与内置模块</h1> <p>浏览器中的 JavaScript 的组成部分</p> <p><img src="https://hasakwebblogimg.oss-cn-hangzhou.aliyuncs.com/202211191510190.png" alt="image.png"></p> <blockquote><p>为什么 JavaScript 可以在浏览器中被执行</p></blockquote> <p>不同的浏览器使用不同的 JavaScript 解析引擎</p> <ul><li>Chrome 浏览器	 =&gt;	V8</li> <li>Firefox 浏览器	   =&gt;	OdinMonkey（奥丁猴）</li> <li>Safri浏览器		    =&gt;	JSCore</li> <li>IE 浏览器			    =&gt;	Chakra（查克拉）</li></ul> <p>其中，Chrome 浏览器的 V8 解析引擎性能最好！</p> <blockquote><p>为什么 JavaScript 可以操作 DOM 和 BOM</p></blockquote> <p><img src="https://hasakwebblogimg.oss-cn-hangzhou.aliyuncs.com/202211191511306.png" alt="image.png"></p> <p>每个浏览器都内置了 DOM、BOM 这样的 API 函数，因此，浏览器中的 JavaScript 才可以调用它们</p> <blockquote><p>浏览器中的 JavaScript 运行环境</p></blockquote> <p>运行环境是指代码正常运行所需的必要环境</p> <p><img src="https://hasakwebblogimg.oss-cn-hangzhou.aliyuncs.com/202211191511822.png" alt="image.png"></p> <p>总结</p> <ul><li>V8 引擎负责解析和执行 JavaScript 代码</li> <li>内置 API 是由运行环境提供的特殊接口，只能在所属的运行环境中被调用</li></ul> <h4 id="node-js-简介"><a href="#node-js-简介" class="header-anchor">#</a> Node.js 简介</h4> <ol><li><p>什么是 Node.js</p> <p><strong>Node.js</strong> 是一个基于 Chrome V8 引擎的 <strong>JavaScript 运行环境</strong></p> <p>官网地址 https://nodejs.org/zh-cn/</p></li> <li><p>Node.js 中的 JavaScript 运行环境</p> <p>a.<strong>浏览器</strong>是 JavaScript 的<strong>前端</strong>运行环境</p> <p>b.<strong>Node.js</strong> 是 JavaScript 的<strong>后端</strong>运行环境</p> <p>c.<strong>Node.js</strong> 中无法调用 DOM 和 BOM 等浏览器内置 API</p></li> <li><p>Node.js 可以做什么</p></li></ol> <blockquote><p>Node.js 作为一个 JavaScript 的运行环境，仅仅提供了基础的功能和 API。然而，基于 Node.js 提供的这些基础能，很多强大的工具和框架如雨后春笋，层出不穷，所以学会了 Node.js ，可以让前端程序员胜任更多的工作和岗位</p></blockquote> <ol><li><p>基于 Express 框架 http://www.expressjs.com.cn/ 可以快速构建 Web 应用</p></li> <li><p>基于 Electron 框架 https://electronjs.org/ 可以构建跨平台的桌面应用</p></li> <li><p>基于 restify 框架 http://restify.com/ 可以快速构建 API 接口项目</p></li> <li><p>读写和操作数据库、创建实用的命令行工具辅助前端开发、etc…</p></li> <li><p>Node.js 怎么学</p></li></ol> <ul><li><p>浏览器中的 JavaScript 学习路径</p> <p>JavaScript 基础语法 + 浏览器内置 API（DOM + BOM） +  第三方库（jQuery、art-template 等）</p></li> <li><p>Node.js 的学习路径</p> <p>JavaScript 基础语法 + <strong>Node.js 内置 API</strong>（fs、path、http等）+ 第三方 API 模块（express、mysql 等）</p></li></ul> <p><strong>Node.js 环境的安装和使用</strong>
如果希望通过 Node.js 来运行 Javascript 代码，则必须在计算机上安装 Node.js 环境才行。
安装包可以从 Node.js 的官网首页直接下载，进入到 Node.js 的官网首页 https://nodejs.org/en/，点击绿色的按钮，下载所需的版本后，双击直接安装即可。</p> <ul><li><p>LTS 为长期稳定版，对于追求稳定性的企业级项目来说，推荐安装 LTS 版本的 Node.js。</p> <ol><li><p>查看已安装的 Node.js 的版本号，终端输入命令 node –v</p></li> <li><p>在 Node.js 环境中执行 JavaScript 代码，终端输入 node 要执行的js文件的路径</p></li></ol></li></ul> <h2 id="_1-2-fs-文件系统模块"><a href="#_1-2-fs-文件系统模块" class="header-anchor">#</a> 1.2 fs 文件系统模块</h2> <h3 id="什么是-fs-文件系统模块"><a href="#什么是-fs-文件系统模块" class="header-anchor">#</a> 什么是 fs 文件系统模块</h3> <p>fs 模块是 Node.js 官方提供的、用来操作文件的模块。提供了一系列的方法和属性，用来满足对文件的操作需求
如果要在 JavaScript 代码中，使用 fs 模块来操作文件，则需要使用如下的方式先导入它</p> <div class="language-javascript line-numbers-mode"><pre class="language-javascript"><code><span class="token keyword">const</span> fs <span class="token operator">=</span> <span class="token function">require</span><span class="token punctuation">(</span><span class="token string">&quot;fs&quot;</span><span class="token punctuation">)</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br></div></div><p><code>fs.readFile(path[, option], callback)</code>读取指定文件中的内容</p> <ul><li><strong>path</strong>	必选参数，字符串，文件路径</li> <li><strong>option</strong>	可选参数，设置字符集</li> <li><strong>callback</strong>	必选参数，文件读取完成后的回调函数</li></ul> <div class="language-javascript line-numbers-mode"><pre class="language-javascript"><code><span class="token comment">// 1. 导入 fs 模块，来操作文件</span>
<span class="token keyword">const</span> fs <span class="token operator">=</span> <span class="token function">require</span><span class="token punctuation">(</span><span class="token string">'fs'</span><span class="token punctuation">)</span>

<span class="token comment">// 2. 调用 fs.readFile() 方法读取文件</span>
<span class="token comment">//    参数1：读取文件的存放路径</span>
<span class="token comment">//    参数2：读取文件时候采用的编码格式，一般默认指定 utf8</span>
<span class="token comment">//    参数3：回调函数，拿到读取失败和成功的结果  err  dataStr</span>
fs<span class="token punctuation">.</span><span class="token function">readFile</span><span class="token punctuation">(</span><span class="token string">'./files/1.txt'</span><span class="token punctuation">,</span> <span class="token string">'utf8'</span><span class="token punctuation">,</span> <span class="token keyword">function</span><span class="token punctuation">(</span><span class="token parameter">err<span class="token punctuation">,</span> dataStr</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
  
  <span class="token comment">// 2.1 打印失败的结果</span>
  <span class="token comment">// 如果读取成功，则 err 的值为 null</span>
  <span class="token comment">// 如果读取失败，则 err 的值为 错误对象，dataStr 的值为 undefined</span>
  console<span class="token punctuation">.</span><span class="token function">log</span><span class="token punctuation">(</span>err<span class="token punctuation">)</span>
  console<span class="token punctuation">.</span><span class="token function">log</span><span class="token punctuation">(</span><span class="token string">'-------'</span><span class="token punctuation">)</span>
  
  <span class="token comment">// 2.2 打印成功的结果</span>
  console<span class="token punctuation">.</span><span class="token function">log</span><span class="token punctuation">(</span>dataStr<span class="token punctuation">)</span>
<span class="token punctuation">}</span><span class="token punctuation">)</span>

fs<span class="token punctuation">.</span><span class="token function">readFile</span><span class="token punctuation">(</span><span class="token string">'./files/11.txt'</span><span class="token punctuation">,</span> <span class="token string">'utf8'</span><span class="token punctuation">,</span> <span class="token keyword">function</span><span class="token punctuation">(</span><span class="token parameter">err<span class="token punctuation">,</span> dataStr</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
  <span class="token keyword">if</span> <span class="token punctuation">(</span>err<span class="token punctuation">)</span> <span class="token punctuation">{</span>
    <span class="token keyword">return</span> console<span class="token punctuation">.</span><span class="token function">log</span><span class="token punctuation">(</span><span class="token string">'读取文件失败！'</span> <span class="token operator">+</span> err<span class="token punctuation">.</span>message<span class="token punctuation">)</span>
  <span class="token punctuation">}</span>
  console<span class="token punctuation">.</span><span class="token function">log</span><span class="token punctuation">(</span><span class="token string">'读取文件成功！'</span> <span class="token operator">+</span> dataStr<span class="token punctuation">)</span>
<span class="token punctuation">}</span><span class="token punctuation">)</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br><span class="line-number">7</span><br><span class="line-number">8</span><br><span class="line-number">9</span><br><span class="line-number">10</span><br><span class="line-number">11</span><br><span class="line-number">12</span><br><span class="line-number">13</span><br><span class="line-number">14</span><br><span class="line-number">15</span><br><span class="line-number">16</span><br><span class="line-number">17</span><br><span class="line-number">18</span><br><span class="line-number">19</span><br><span class="line-number">20</span><br><span class="line-number">21</span><br><span class="line-number">22</span><br><span class="line-number">23</span><br><span class="line-number">24</span><br><span class="line-number">25</span><br></div></div><p><code>fs.writeFile(path, data[, option], callback)</code>向指定的文件中写入内容</p> <ul><li><code>path</code>	必选参数，字符串，文件路径</li> <li><code>data</code>	必选参数，写入的内容</li> <li><code>option</code>	可选参数，设置字符集，默认值是 utf8</li> <li><code>callback</code>	必选参数，文件写入完成后的回调函数</li> <li>注意：写入会覆盖原内容</li></ul> <div class="language-javascript line-numbers-mode"><pre class="language-javascript"><code><span class="token keyword">const</span> fs <span class="token operator">=</span> <span class="token function">require</span><span class="token punctuation">(</span><span class="token string">'fs'</span><span class="token punctuation">)</span>

<span class="token comment">// 2. 调用 fs.writeFile() 方法，写入文件的内容</span>
<span class="token comment">//    参数1：表示文件的存放路径</span>
<span class="token comment">//    参数2：表示要写入的内容</span>
<span class="token comment">//    参数3：回调函数</span>
fs<span class="token punctuation">.</span><span class="token function">writeFile</span><span class="token punctuation">(</span><span class="token string">'./files/3.txt'</span><span class="token punctuation">,</span> <span class="token string">'ok123'</span><span class="token punctuation">,</span> <span class="token keyword">function</span><span class="token punctuation">(</span><span class="token parameter">err</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
  <span class="token comment">// 2.1 如果文件写入成功，则 err 的值等于 null</span>
  <span class="token comment">// 2.2 如果文件写入失败，则 err 的值等于一个 错误对象</span>
  <span class="token comment">// console.log(err)</span>

  <span class="token keyword">if</span> <span class="token punctuation">(</span>err<span class="token punctuation">)</span> <span class="token punctuation">{</span>
    <span class="token keyword">return</span> console<span class="token punctuation">.</span><span class="token function">log</span><span class="token punctuation">(</span><span class="token string">'文件写入失败！'</span> <span class="token operator">+</span> err<span class="token punctuation">.</span>message<span class="token punctuation">)</span>
  <span class="token punctuation">}</span>
  console<span class="token punctuation">.</span><span class="token function">log</span><span class="token punctuation">(</span><span class="token string">'文件写入成功！'</span><span class="token punctuation">)</span>
<span class="token punctuation">}</span><span class="token punctuation">)</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br><span class="line-number">7</span><br><span class="line-number">8</span><br><span class="line-number">9</span><br><span class="line-number">10</span><br><span class="line-number">11</span><br><span class="line-number">12</span><br><span class="line-number">13</span><br><span class="line-number">14</span><br><span class="line-number">15</span><br><span class="line-number">16</span><br></div></div><p><code>__dirname</code> 表示当前文件所处的目录</p> <div class="language-javascript line-numbers-mode"><pre class="language-javascript"><code>console<span class="token punctuation">.</span><span class="token function">log</span><span class="token punctuation">(</span>__dirname<span class="token punctuation">)</span>

fs<span class="token punctuation">.</span><span class="token function">readFile</span><span class="token punctuation">(</span>__dirname <span class="token operator">+</span> <span class="token string">'/files/1.txt'</span><span class="token punctuation">,</span> <span class="token string">'utf8'</span><span class="token punctuation">,</span> <span class="token keyword">function</span><span class="token punctuation">(</span><span class="token parameter">err<span class="token punctuation">,</span> dataStr</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
  <span class="token keyword">if</span> <span class="token punctuation">(</span>err<span class="token punctuation">)</span> <span class="token punctuation">{</span>
    <span class="token keyword">return</span> console<span class="token punctuation">.</span><span class="token function">log</span><span class="token punctuation">(</span><span class="token string">'读取文件失败！'</span> <span class="token operator">+</span> err<span class="token punctuation">.</span>message<span class="token punctuation">)</span>
  <span class="token punctuation">}</span>
  console<span class="token punctuation">.</span><span class="token function">log</span><span class="token punctuation">(</span><span class="token string">'读取文件成功！'</span> <span class="token operator">+</span> dataStr<span class="token punctuation">)</span>
<span class="token punctuation">}</span><span class="token punctuation">)</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br><span class="line-number">7</span><br><span class="line-number">8</span><br></div></div><h2 id="_1-3-path-路径模块"><a href="#_1-3-path-路径模块" class="header-anchor">#</a> 1.3 path 路径模块</h2> <p>path 模块是 Node.js 官方提供的、用来处理路径的模块。提供一系列的方法和属性，用来满足对路径的处理需求
如果要在 JavaScript 代码中，使用 path 模块来处理路径，则需要使用如下的方式先导入它</p> <div class="language-javascript line-numbers-mode"><pre class="language-javascript"><code><span class="token keyword">const</span> path <span class="token operator">=</span> <span class="token function">require</span><span class="token punctuation">(</span><span class="token string">&quot;path&quot;</span><span class="token punctuation">)</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br></div></div><p><code>path.join(...paths)</code>可以把多个路径片段拼接为完整的路径字符串</p> <ul><li><code>...paths &lt;string&gt;</code>路径片段的序列</li> <li>返回 <code>&lt;string&gt;</code></li> <li>**注意：**凡是涉及到路径拼接的操作，都要使用 path.join() 方法进行处理。不直接使用 + 进行字符串的拼接</li></ul> <div class="language-javascript line-numbers-mode"><pre class="language-javascript"><code><span class="token keyword">const</span> path <span class="token operator">=</span> <span class="token function">require</span><span class="token punctuation">(</span><span class="token string">'path'</span><span class="token punctuation">)</span>
<span class="token keyword">const</span> fs <span class="token operator">=</span> <span class="token function">require</span><span class="token punctuation">(</span><span class="token string">'fs'</span><span class="token punctuation">)</span>

<span class="token comment">// 注意：  ../ 会抵消前面的路径</span>
<span class="token keyword">const</span> pathStr <span class="token operator">=</span> path<span class="token punctuation">.</span><span class="token function">join</span><span class="token punctuation">(</span><span class="token string">'/a'</span><span class="token punctuation">,</span> <span class="token string">'/b/c'</span><span class="token punctuation">,</span> <span class="token string">'../../'</span><span class="token punctuation">,</span> <span class="token string">'./d'</span><span class="token punctuation">,</span> <span class="token string">'e'</span><span class="token punctuation">)</span>
console<span class="token punctuation">.</span><span class="token function">log</span><span class="token punctuation">(</span>pathStr<span class="token punctuation">)</span>  <span class="token comment">// \a\b\d\e</span>

<span class="token comment">// 取代fs.readFile(__dirname + '/files/1.txt', ...)</span>
fs<span class="token punctuation">.</span><span class="token function">readFile</span><span class="token punctuation">(</span>path<span class="token punctuation">.</span><span class="token function">join</span><span class="token punctuation">(</span>__dirname<span class="token punctuation">,</span> <span class="token string">'./files/1.txt'</span><span class="token punctuation">)</span><span class="token punctuation">,</span> <span class="token string">'utf8'</span><span class="token punctuation">,</span> <span class="token keyword">function</span><span class="token punctuation">(</span><span class="token parameter">err<span class="token punctuation">,</span> dataStr</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
  <span class="token keyword">if</span> <span class="token punctuation">(</span>err<span class="token punctuation">)</span> <span class="token punctuation">{</span>
    <span class="token keyword">return</span> console<span class="token punctuation">.</span><span class="token function">log</span><span class="token punctuation">(</span>err<span class="token punctuation">.</span>message<span class="token punctuation">)</span>
  <span class="token punctuation">}</span>
  console<span class="token punctuation">.</span><span class="token function">log</span><span class="token punctuation">(</span>dataStr<span class="token punctuation">)</span>
<span class="token punctuation">}</span><span class="token punctuation">)</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br><span class="line-number">7</span><br><span class="line-number">8</span><br><span class="line-number">9</span><br><span class="line-number">10</span><br><span class="line-number">11</span><br><span class="line-number">12</span><br><span class="line-number">13</span><br><span class="line-number">14</span><br></div></div><p><code>path.basename(path[, ext])</code>可以获取路径中的最后一部分，经常通过这个方法获取路径中的文件名</p> <ul><li><code>path &lt;string&gt;</code>	  必选参数，表示一个路径的字符串</li> <li><code>ext &lt;string&gt;</code>		可选参数，表示文件扩展名</li> <li><code>返回 &lt;string&gt;</code>        路径的最后一部分</li></ul> <div class="language-javascript line-numbers-mode"><pre class="language-javascript"><code><span class="token keyword">const</span> path <span class="token operator">=</span> <span class="token function">require</span><span class="token punctuation">(</span><span class="token string">'path'</span><span class="token punctuation">)</span>

<span class="token comment">// 定义文件的存放路径</span>
<span class="token keyword">const</span> fpath <span class="token operator">=</span> <span class="token string">'/a/b/c/index.html'</span>

<span class="token keyword">const</span> fullName <span class="token operator">=</span> path<span class="token punctuation">.</span><span class="token function">basename</span><span class="token punctuation">(</span>fpath<span class="token punctuation">)</span>
console<span class="token punctuation">.</span><span class="token function">log</span><span class="token punctuation">(</span>fullName<span class="token punctuation">)</span> <span class="token comment">// index.html</span>

<span class="token keyword">const</span> nameWithoutExt <span class="token operator">=</span> path<span class="token punctuation">.</span><span class="token function">basename</span><span class="token punctuation">(</span>fpath<span class="token punctuation">,</span> <span class="token string">'.html'</span><span class="token punctuation">)</span>
console<span class="token punctuation">.</span><span class="token function">log</span><span class="token punctuation">(</span>nameWithoutExt<span class="token punctuation">)</span> <span class="token comment">// index</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br><span class="line-number">7</span><br><span class="line-number">8</span><br><span class="line-number">9</span><br><span class="line-number">10</span><br></div></div><p>path.extname(path)可以获取路径中的扩展名部分</p> <ul><li><code>path &lt;string&gt;</code>	必选参数，表示一个路径的字符串</li> <li><code>返回 &lt;string&gt;</code>	返回得到的扩展名字符串</li></ul> <div class="language-javascript line-numbers-mode"><pre class="language-javascript"><code><span class="token keyword">const</span> path <span class="token operator">=</span> <span class="token function">require</span><span class="token punctuation">(</span><span class="token string">'path'</span><span class="token punctuation">)</span>

<span class="token comment">// 这是文件的存放路径</span>
<span class="token keyword">const</span> fpath <span class="token operator">=</span> <span class="token string">'/a/b/c/index.html'</span>

<span class="token keyword">const</span> fext <span class="token operator">=</span> path<span class="token punctuation">.</span><span class="token function">extname</span><span class="token punctuation">(</span>fpath<span class="token punctuation">)</span>
console<span class="token punctuation">.</span><span class="token function">log</span><span class="token punctuation">(</span>fext<span class="token punctuation">)</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br><span class="line-number">7</span><br></div></div><h2 id="_1-4-http-模块"><a href="#_1-4-http-模块" class="header-anchor">#</a> 1.4 http 模块</h2> <p>http 模块是 Node.js 官方提供的用来创建 web 服务器的模块
通过 http 模块提供的<code>http.createServer()</code> 方法，就能方便的把一台普通的电脑，变成一台 Web 服务器，从而对外提供 Web 资源服务。在 Node.js 中，不需要使用 IIS、Apache 等第三方 web 服务器软件，而是基于 Node.js 提供的 http 模块，通过几行简单的代码，就能轻松的手写一个服务器软件，从而对外提供 web 服务
导入 http 模块创建 Web 服务器</p> <div class="language-javascript line-numbers-mode"><pre class="language-javascript"><code><span class="token keyword">const</span> http <span class="token operator">=</span> <span class="token function">require</span><span class="token punctuation">(</span><span class="token string">&quot;http&quot;</span><span class="token punctuation">)</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br></div></div><p><strong>服务器相关的概念</strong></p> <p><strong>IP 地址</strong></p> <blockquote><p>就是互联网上每台计算机的唯一地址，因此 IP 地址具有唯一性。如果把“个人电脑”比作“一台电话”，那么“IP地址”就相当于“电话号码”，只有在知道对方 IP 地址的前提下，才能与对应的电脑之间进行数据通信。
IP 地址的格式：通常用“点分十进制”表示成（a.b.c.d）的形式，其中，a,b,c,d都是 0~255 之间的十进制整数。例如：用点分十进表示的 IP地址（192.168.1.1）
注意</p> <ul><li>互联网中每台 Web 服务器，都有自己的 IP 地址，如：可以在 Windows 的终端中运行 ping www.baidu.com 命令，即可查看到百度服务器的 IP 地址</li> <li>在开发期间，自己的电脑既是一台服务器，也是一个客户端，为了方便测试，可以在自己的浏览器中输入 127.0.0.1 这个 IP 地址，就能把自己的电脑当做一台服务器进行访问了</li></ul></blockquote> <p><strong>域名和域名服务器</strong></p> <blockquote><p>尽管 IP 地址能够唯一地标记网络上的计算机，但IP地址是一长串数字，不直观，而且不便于记忆，于是人们又发明了另一套字符型的地址方案，即所谓的域名（Domain Name）地址。
IP地址和域名是一一对应的关系，这份对应关系存放在一种叫做域名服务器(DNS，Domain name server)的电脑中。使用者只需通过好记的域名访问对应的服务器即可，对应的转换工作由域名服务器实现。因此，域名服务器就是提供 IP 地址和域名之间的转换服务的服务器。
注意</p> <ul><li>单纯使用 IP 地址，互联网中的电脑也能够正常工作。但是有了域名的加持，能让互联网的世界变得更加方便</li> <li>在开发测试期间， 127.0.0.1对应的域名是 localhost，都代表自己的这台电脑，在使用效果上没有任何区别</li></ul></blockquote> <p><strong>端口号</strong></p> <blockquote><p>计算机中的端口号，就好像是现实生活中的门牌号一样。通过门牌号，外卖小哥可以在整栋大楼众多的房间中，准确把外卖送到你的手中。
同样的道理，在一台电脑中，可以运行成百上千个 web 服务。每个 web 服务都对应一个唯一的端口号。客户端发送过来的网络请求，通过端口号，可以被准确地交给对应的 web 服务进行处理。
注意</p> <ul><li>每个端口号不能同时被多个 web 服务占用</li> <li>在实际应用中，URL 中的 80 端口可以被省略</li></ul></blockquote> <p><strong>创建最基本的 web 服务器</strong></p> <p><strong>创建 web 服务器的基本步骤</strong></p> <ol><li>导入 http 模块</li> <li>创建 web 服务器实例</li> <li>server.on()为服务器实例绑定 request事件，监听客户端的请求</li> <li>启动服务器</li></ol> <div class="language-javascript line-numbers-mode"><pre class="language-javascript"><code><span class="token comment">// 1. 导入 http 模块</span>
<span class="token keyword">const</span> http <span class="token operator">=</span> <span class="token function">require</span><span class="token punctuation">(</span><span class="token string">'http'</span><span class="token punctuation">)</span>

<span class="token comment">// 2. 创建 web 服务器实例</span>
<span class="token keyword">const</span> server <span class="token operator">=</span> http<span class="token punctuation">.</span><span class="token function">createServer</span><span class="token punctuation">(</span><span class="token punctuation">)</span>

<span class="token comment">// 3. 为服务器实例绑定 request 事件，监听客户端的请求</span>
server<span class="token punctuation">.</span><span class="token function">on</span><span class="token punctuation">(</span><span class="token string">'request'</span><span class="token punctuation">,</span> <span class="token keyword">function</span> <span class="token punctuation">(</span><span class="token parameter">req<span class="token punctuation">,</span> res</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
  console<span class="token punctuation">.</span><span class="token function">log</span><span class="token punctuation">(</span><span class="token string">'Someone visit our web server.'</span><span class="token punctuation">)</span>
<span class="token punctuation">}</span><span class="token punctuation">)</span>

<span class="token comment">// 4. 启动服务器</span>
server<span class="token punctuation">.</span><span class="token function">listen</span><span class="token punctuation">(</span><span class="token number">8080</span><span class="token punctuation">,</span> <span class="token keyword">function</span> <span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>  
  console<span class="token punctuation">.</span><span class="token function">log</span><span class="token punctuation">(</span><span class="token string">'server running at http://127.0.0.1:8080'</span><span class="token punctuation">)</span>
<span class="token punctuation">}</span><span class="token punctuation">)</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br><span class="line-number">7</span><br><span class="line-number">8</span><br><span class="line-number">9</span><br><span class="line-number">10</span><br><span class="line-number">11</span><br><span class="line-number">12</span><br><span class="line-number">13</span><br><span class="line-number">14</span><br><span class="line-number">15</span><br></div></div><p><strong>req请求对象</strong></p> <p>只要服务器接收到了客户端的请求，就会调用通过 server.on() 为服务器绑定的 request 事件处理函数</p> <p><strong>res响应对象</strong>
在服务器 request 事件处理函数中，如果想访问与服务器相关的数据或属性，通过<code>res.end(data)</code>方法响应</p> <div class="language-javascript line-numbers-mode"><pre class="language-javascript"><code>server<span class="token punctuation">.</span><span class="token function">on</span><span class="token punctuation">(</span><span class="token string">'request'</span><span class="token punctuation">,</span> <span class="token punctuation">(</span><span class="token parameter">req<span class="token punctuation">,</span> res</span><span class="token punctuation">)</span> <span class="token operator">=&gt;</span> <span class="token punctuation">{</span>
  <span class="token comment">// req.url 是客户端请求的 URL 地址</span>
  <span class="token keyword">const</span> url <span class="token operator">=</span> req<span class="token punctuation">.</span>url
  <span class="token comment">// req.method 是客户端请求的 method 类型</span>
  <span class="token keyword">const</span> method <span class="token operator">=</span> req<span class="token punctuation">.</span>method
  <span class="token keyword">const</span> str <span class="token operator">=</span> <span class="token template-string"><span class="token template-punctuation string">`</span><span class="token string">Your request url is </span><span class="token interpolation"><span class="token interpolation-punctuation punctuation">${</span>url<span class="token interpolation-punctuation punctuation">}</span></span><span class="token string">, and request method is </span><span class="token interpolation"><span class="token interpolation-punctuation punctuation">${</span>method<span class="token interpolation-punctuation punctuation">}</span></span><span class="token template-punctuation string">`</span></span>
  console<span class="token punctuation">.</span><span class="token function">log</span><span class="token punctuation">(</span>str<span class="token punctuation">)</span>
  
  <span class="token comment">// 调用 res.end() 方法，向客户端响应一些内容</span>
  res<span class="token punctuation">.</span><span class="token function">end</span><span class="token punctuation">(</span>str<span class="token punctuation">)</span>
<span class="token punctuation">}</span><span class="token punctuation">)</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br><span class="line-number">7</span><br><span class="line-number">8</span><br><span class="line-number">9</span><br><span class="line-number">10</span><br><span class="line-number">11</span><br></div></div><p><strong>解决中文乱码问题</strong></p> <p>当调用 res.end() 方法，向客户端发送中文内容的时候，会出现乱码问题，此时，需要手动设置内容的编码格式</p> <div class="language-javascript line-numbers-mode"><pre class="language-javascript"><code>
server<span class="token punctuation">.</span><span class="token function">on</span><span class="token punctuation">(</span><span class="token string">'request'</span><span class="token punctuation">,</span> <span class="token punctuation">(</span><span class="token parameter">req<span class="token punctuation">,</span> res</span><span class="token punctuation">)</span> <span class="token operator">=&gt;</span> <span class="token punctuation">{</span>
  <span class="token comment">// 定义一个字符串，包含中文的内容</span>
  <span class="token keyword">const</span> str <span class="token operator">=</span> <span class="token template-string"><span class="token template-punctuation string">`</span><span class="token string">您请求的 URL 地址是 </span><span class="token interpolation"><span class="token interpolation-punctuation punctuation">${</span>req<span class="token punctuation">.</span>url<span class="token interpolation-punctuation punctuation">}</span></span><span class="token string">，请求的 method 类型为 </span><span class="token interpolation"><span class="token interpolation-punctuation punctuation">${</span>req<span class="token punctuation">.</span>method<span class="token interpolation-punctuation punctuation">}</span></span><span class="token template-punctuation string">`</span></span>
  
  <span class="token comment">// 调用 res.setHeader() 方法，设置 Content-Type 响应头，解决中文乱码的问题</span>
  res<span class="token punctuation">.</span><span class="token function">setHeader</span><span class="token punctuation">(</span><span class="token string">'Content-Type'</span><span class="token punctuation">,</span> <span class="token string">'text/html; charset=utf-8'</span><span class="token punctuation">)</span>
  
  <span class="token comment">// res.end() 将内容响应给客户端</span>
  res<span class="token punctuation">.</span><span class="token function">end</span><span class="token punctuation">(</span>str<span class="token punctuation">)</span>
<span class="token punctuation">}</span><span class="token punctuation">)</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br><span class="line-number">7</span><br><span class="line-number">8</span><br><span class="line-number">9</span><br><span class="line-number">10</span><br><span class="line-number">11</span><br></div></div><p><strong>实例</strong>
根据不同的 url 响应不同的 html 内容
<strong>步骤</strong></p> <ol><li>获取请求的 url地址</li> <li>设置默认的响应内容为 404 Not found</li> <li>判断用户请求的是否为 / 或 /index.html 首页</li> <li>判断用户请求的是否为 /about.html 关于页面</li> <li>设置 Content-Type 响应头，防止中文乱码</li> <li>使用 res.end() 把内容响应给客户端</li></ol> <div class="language-javascript line-numbers-mode"><pre class="language-javascript"><code><span class="token keyword">const</span> http <span class="token operator">=</span> <span class="token function">require</span><span class="token punctuation">(</span><span class="token string">'http'</span><span class="token punctuation">)</span>
<span class="token keyword">const</span> server <span class="token operator">=</span> http<span class="token punctuation">.</span><span class="token function">createServer</span><span class="token punctuation">(</span><span class="token punctuation">)</span>

server<span class="token punctuation">.</span><span class="token function">on</span><span class="token punctuation">(</span><span class="token string">'request'</span><span class="token punctuation">,</span> <span class="token punctuation">(</span><span class="token parameter">req<span class="token punctuation">,</span> res</span><span class="token punctuation">)</span> <span class="token operator">=&gt;</span> <span class="token punctuation">{</span>
  <span class="token comment">// 1. 获取请求的 url 地址</span>
  <span class="token keyword">const</span> url <span class="token operator">=</span> req<span class="token punctuation">.</span>url
  
  <span class="token comment">// 2. 设置默认的响应内容为 404 Not found</span>
  <span class="token keyword">let</span> content <span class="token operator">=</span> <span class="token string">'&lt;h1&gt;404 Not found!&lt;/h1&gt;'</span>
  
  <span class="token comment">// 3. 判断用户请求的是否为 / 或 /index.html 首页</span>
  <span class="token comment">// 4. 判断用户请求的是否为 /about.html 关于页面</span>
  <span class="token keyword">if</span> <span class="token punctuation">(</span>url <span class="token operator">===</span> <span class="token string">'/'</span> <span class="token operator">||</span> url <span class="token operator">===</span> <span class="token string">'/index.html'</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
    content <span class="token operator">=</span> <span class="token string">'&lt;h1&gt;首页&lt;/h1&gt;'</span>
  <span class="token punctuation">}</span> <span class="token keyword">else</span> <span class="token keyword">if</span> <span class="token punctuation">(</span>url <span class="token operator">===</span> <span class="token string">'/about.html'</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
    content <span class="token operator">=</span> <span class="token string">'&lt;h1&gt;关于页面&lt;/h1&gt;'</span>
  <span class="token punctuation">}</span>
  
  <span class="token comment">// 5. 设置 Content-Type 响应头，防止中文乱码</span>
  res<span class="token punctuation">.</span><span class="token function">setHeader</span><span class="token punctuation">(</span><span class="token string">'Content-Type'</span><span class="token punctuation">,</span> <span class="token string">'text/html; charset=utf-8'</span><span class="token punctuation">)</span>
  
  <span class="token comment">// 6. 使用 res.end() 把内容响应给客户端</span>
  res<span class="token punctuation">.</span><span class="token function">end</span><span class="token punctuation">(</span>content<span class="token punctuation">)</span>
<span class="token punctuation">}</span><span class="token punctuation">)</span>

server<span class="token punctuation">.</span><span class="token function">listen</span><span class="token punctuation">(</span><span class="token number">80</span><span class="token punctuation">,</span> <span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">=&gt;</span> <span class="token punctuation">{</span>
  console<span class="token punctuation">.</span><span class="token function">log</span><span class="token punctuation">(</span><span class="token string">'server running at http://127.0.0.1'</span><span class="token punctuation">)</span>
<span class="token punctuation">}</span><span class="token punctuation">)</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br><span class="line-number">7</span><br><span class="line-number">8</span><br><span class="line-number">9</span><br><span class="line-number">10</span><br><span class="line-number">11</span><br><span class="line-number">12</span><br><span class="line-number">13</span><br><span class="line-number">14</span><br><span class="line-number">15</span><br><span class="line-number">16</span><br><span class="line-number">17</span><br><span class="line-number">18</span><br><span class="line-number">19</span><br><span class="line-number">20</span><br><span class="line-number">21</span><br><span class="line-number">22</span><br><span class="line-number">23</span><br><span class="line-number">24</span><br><span class="line-number">25</span><br><span class="line-number">26</span><br><span class="line-number">27</span><br><span class="line-number">28</span><br></div></div></div></section> <footer class="page-edit"><!----> <!----></footer> <!----> <div class="comments-wrapper"><!----></div></main></div> <!----></div> <ul class="sub-sidebar sub-sidebar-wrapper" style="width:0;" data-v-b57cc07c data-v-7dd95ae2></ul></div></div></div><div class="global-ui"><div class="back-to-ceiling" style="right:1rem;bottom:6rem;width:2.5rem;height:2.5rem;border-radius:.25rem;line-height:2.5rem;display:none;" data-v-c6073ba8 data-v-c6073ba8><svg t="1574745035067" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="5404" class="icon" data-v-c6073ba8><path d="M526.60727968 10.90185116a27.675 27.675 0 0 0-29.21455937 0c-131.36607665 82.28402758-218.69155461 228.01873535-218.69155402 394.07834331a462.20625001 462.20625001 0 0 0 5.36959153 69.94390903c1.00431239 6.55289093-0.34802892 13.13561351-3.76865779 18.80351572-32.63518765 54.11355614-51.75690182 118.55860487-51.7569018 187.94566865a371.06718723 371.06718723 0 0 0 11.50484808 91.98906777c6.53300375 25.50556257 41.68394495 28.14064038 52.69160883 4.22606766 17.37162448-37.73630017 42.14135425-72.50938081 72.80769204-103.21549295 2.18761121 3.04276886 4.15646224 6.24463696 6.40373557 9.22774369a1871.4375 1871.4375 0 0 0 140.04691725 5.34970492 1866.36093723 1866.36093723 0 0 0 140.04691723-5.34970492c2.24727335-2.98310674 4.21612437-6.18497483 6.3937923-9.2178004 30.66633723 30.70611158 55.4360664 65.4791928 72.80769147 103.21549355 11.00766384 23.91457269 46.15860503 21.27949489 52.69160879-4.22606768a371.15156223 371.15156223 0 0 0 11.514792-91.99901164c0-69.36717486-19.13165746-133.82216804-51.75690182-187.92578088-3.42062944-5.66790279-4.76302748-12.26056868-3.76865837-18.80351632a462.20625001 462.20625001 0 0 0 5.36959269-69.943909c-0.00994388-166.08943902-87.32547796-311.81420293-218.6915546-394.09823051zM605.93803103 357.87693858a93.93749974 93.93749974 0 1 1-187.89594924 6.1e-7 93.93749974 93.93749974 0 0 1 187.89594924-6.1e-7z" p-id="5405" data-v-c6073ba8></path><path d="M429.50777625 765.63860547C429.50777625 803.39355007 466.44236686 1000.39046097 512.00932183 1000.39046097c45.56695499 0 82.4922232-197.00623328 82.5015456-234.7518555 0-37.75494459-36.9345906-68.35043303-82.4922232-68.34111062-45.57627738-0.00932239-82.52019037 30.59548842-82.51086798 68.34111062z" p-id="5406" data-v-c6073ba8></path></svg></div></div></div>
    <script src="/assets/js/app.c7915c77.js" defer></script><script src="/assets/js/3.f80332a6.js" defer></script><script src="/assets/js/1.5cffa4a1.js" defer></script><script src="/assets/js/44.d579b00f.js" defer></script>
  </body>
</html>
